package zhou.chs.p5_2;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,View.OnClickListener{
    //定义控件
    ListView lv;                 //列表显示蓝牙设备
    TextView tvSta;             //显示状态信息
    Button btList,btStart;    //按键
    ImageView wave;             //显示波形
    //变量定义
    private BluetoothAdapter btAdapter;         	//蓝牙适配器
    private BluetoothDevice btDevice;           	//蓝牙设备
    private Set<BluetoothDevice> pairedBts;     //配对蓝牙设备集合
    private BluetoothSocket btSocket = null;    //蓝牙socket
    private Handler myhandler;              		//信息通道
    private LinkThread mlink;               		//自定义连接线程
    private ComThread mcom;                 		//自定义数据通信线程
    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public byte rbuf[] = new byte[600];        	//接收缓冲区
    int len;   //接收字节长度
    boolean isConnect;   //已连接状态
    boolean pause=false;   //暂停
    int ma,mv,ms,mu;    //当前测量值
    int[] wa = new int[125];            //振动加速度曲线缓冲区
    int[] wf = new int[125];            //频谱曲线缓冲区
    private Bitmap bitmap;      //图片
    private Canvas canvas;      //画布
    private int myX;        //画布宽度
    private int myY;        //画布高度
    private Paint paint;        //画笔
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvSta = (TextView) findViewById(R.id.idtv);    //控件实例化
        btList = (Button) findViewById(R.id.idList);
        btStart = (Button) findViewById(R.id.idStart);
        wave= (ImageView) findViewById(R.id.idiv);
        btStart.setOnClickListener(this);    //注册按钮单击监听事件
        btStart.setEnabled(false);
        btList.setOnClickListener(this);
        lv = (ListView) findViewById(R.id.idbl);
        lv.setOnItemClickListener(this);    //注册列表选项单击监听事件
        myhandler = new MyHandler();        //实例化Handler，用于进程间的通信
        btAdapter = BluetoothAdapter.getDefaultAdapter();   //蓝牙适配器
        //屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
    //响应按键单击事件
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.idList:        //蓝牙列表按钮
                pairedBts = btAdapter.getBondedDevices();   //获得已配对蓝牙设备集合
                ArrayList bt_list = new ArrayList();
                lv.setEnabled(true);
                if (!btAdapter.isEnabled()) {           //当前蓝牙适配器不可用
                    Intent turnOn = new
                            Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(turnOn, 0);    //调用打开蓝牙适配器程序
                    tvSta.setText("打开蓝牙适配器");
                } else {
                    tvSta.setText("蓝牙适配器已打开");
                }
                for(BluetoothDevice bt : pairedBts){ //已配对蓝牙设备集合转为列表
                    bt_list.add(bt.getName() + "\n" + bt.getAddress());
                }               //列表放入适配器
                final ArrayAdapter adapter = new ArrayAdapter
                        (this, android.R.layout.simple_list_item_1, bt_list);
                lv.setAdapter(adapter);  //通过适配器在ListView上显示配对蓝牙设备列表
                tvSta.setText("选择蓝牙设备");
                break;
            case R.id.idStart:          //开始按钮
                    if(pause){
                        btStart.setText("暂停");
                        pause=false;
                    }else {
                        btStart.setText("开始");
                        pause=true;
                    }
                break;
        }
    }
    //响应列表单击选项事件
    public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
        TextView txv = (TextView) view;  //获取选中项文本
        String s = txv.getText().toString();
        String[] addr = s.split("\n");   //抽取MAC地址
        try {        //通过MAC地址获得蓝牙设备
            btDevice = btAdapter.getRemoteDevice(addr[1]);
            lv.setEnabled(false);
        } catch (Exception e) {
            tvSta.setText("获取设备失败");
        }
        mlink = new LinkThread(btDevice);  //在蓝牙设备连接线程中加载蓝牙设备
        mlink.start();   //启动连接蓝牙设备线程
    }
    //连接蓝牙装置
    private class LinkThread extends Thread {
        public LinkThread(BluetoothDevice mDevice) {
            btSocket = null;
            try {   //定义Socket为蓝牙串口服务
                btSocket = mDevice.createRfcommSocketToServiceRecord(uuid);
            } catch (Exception e) {
            }
        }
        public final void run() {
            btAdapter.cancelDiscovery();
            try {
                btSocket.connect();       //建立Socket连接
                isConnect = true;
                mcom = new ComThread(btSocket);
                mcom.start();       		//建立连接后启动建立数据通信线程
                Message msg = myhandler.obtainMessage();
                msg.what = 1;
                myhandler.sendMessage(msg);    //通知主线程可以开始通信
            } catch (IOException e1) {
                isConnect = false;
                try {
                    btSocket.close();   //关闭蓝牙连接
                    btSocket = null;
                } catch (IOException e2) {
                }
            }
        }
    }
    //在主线程处理Handler传回来的message
    class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:   //成功连接蓝牙
                    tvSta.setText("已连接蓝牙");
                    btStart.setEnabled(true);
                    break;
                case 2:     //收到蓝牙数据
                    len=0;
                    if(rbuf[1]==0x03){
                        ma=((rbuf[2]&0xFF)<<8)|(rbuf[3]&0xFF); //振动加速度
                        mv=((rbuf[4]&0xFF)<<8)|(rbuf[5]&0xFF); //振动速度
                        ms=((rbuf[6]&0xFF)<<8)|(rbuf[7]&0xFF); //振动幅度
                        mu=rbuf[9]&0xFF;
                        for(int i=0;i<125;i++){
                            wa[i]=((rbuf[2*i+10]&0xFF)<<8)|(rbuf[2*i+11]&0xFF);  //加速度波形
                            wf[i]=((rbuf[2*i+260]&0xFF)<<8)|(rbuf[2*i+261]&0xFF);   //频谱波形
                        }
                        if(pause){
                            tvSta.setText("暂停。。。");
                        }else {
                            Show();
                            tvSta.setText(String.format("电池电压：%.1fV",(float)mu/10));
                        }
                    }
                    break;
            }
        }
    }
    //数据通信线程
    private class ComThread extends Thread {
        private final BluetoothSocket mSocket;
        private final InputStream mInStream;    //定义输入流
        private final OutputStream mOutStream;  //定义输出流
        public ComThread(BluetoothSocket socket) {   //socket连接
            mSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = mSocket.getInputStream();      //Socket输入数据流
                tmpOut = mSocket.getOutputStream();    //Socket输出数据流
            } catch (IOException e) {
            }
            mInStream = tmpIn;
            mOutStream = tmpOut;
        }
        //阻塞线程接收数据
        public final void run() {
            byte[] buf = new byte[600];  // 接收数据临时缓冲区
            while (isConnect) {
                try {
                    int byt = mInStream.read(buf);
                    for (int i = 0; i < byt; i++) rbuf[len + i] = buf[i];  // 收到数据后转移到待处理存储区
                    len = len + byt;         //数据分段接收，字节数累计
                    if (len > 510) {
                        Message msg = myhandler.obtainMessage();
                        msg.what = 2;
                        myhandler.sendMessage(msg); // 通知主线程接收到数据
                    }
                    try {
                        sleep(50);     //延时50ms，等接收区数据处理完毕
                    } catch (InterruptedException e) {
                    }
                } catch (NullPointerException e) {
                    isConnect = false;
                    break;
                } catch (IOException e) {
                    break;
                }
            }
        }
        //发送字节数据
        public void write(byte[] bytes) {
            try {
                mOutStream.write(bytes);
            } catch (IOException e) {
            }
        }
        //关闭蓝牙连接
        public void cancel() {
            try {
                mSocket.close();
            } catch (IOException e) {
            }
        }
    }
    //显示波形
    public void Show() {
        myX=wave.getWidth();
        myY=wave.getHeight();
        if (bitmap == null) {                //创建一个新的bitmap对象，宽、高使用界面布局中ImageView对象的宽、高
            bitmap = Bitmap.createBitmap(myX, myY, Bitmap.Config.RGB_565);
        }
        canvas = new Canvas(bitmap);        //根据bitmap对象创建一个画布
        canvas.drawColor(Color.WHITE);      //设置画布背景色为白色    //canvas.drawRect(0,0,736,512,paint);
        paint = new Paint();                //创建一个画笔对象

        paint.setStrokeWidth(2);            //设置画笔的线条粗细为2磅
        paint.setColor(Color.LTGRAY);         //画背景网格
        canvas.drawLine(0,myY/2,myX,myY/2,paint);
        for(int i=1;i<5;i++){
            canvas.drawLine(i*myX/5,0,i*myX/5,myY,paint);
        }
        for(int i=1;i<25;i++){
            canvas.drawLine(i*myX/25,myY/2-10,i*myX/25,myY/2+10,paint);
        }
        paint.setColor(Color.BLACK); //振动波形曲线，黑色
        for(char i=1;i<125;i++){
            canvas.drawLine((i-1)*myX/125, wa[i-1]*myY/1024, i*myX/125,wa[i]*myY/1024,paint);
        }
        paint.setColor(Color.RED);			//FFT曲线，红色
        for(char i=1;i<125;i++){
            canvas.drawLine((i-1)*myX/125, myY-(wf[i-1])*myY/1024, i*myX/125,myY-(wf[i])*myY/1024,paint);
        }
        //显示测量值
        paint.setColor(Color.RED);
        paint.setTextSize(48);
        canvas.drawText(String.format("加速度：%.1fm/s2",(float)ma/10),300,60,paint);
        canvas.drawText(String.format("速度：%.1fmm/s",(float)mv/10),300,120,paint);
        canvas.drawText(String.format("位移：%.3fmm",(float)ms/1000),300,180,paint);
        //显示频谱坐标
        paint.setColor(Color.LTGRAY);
        paint.setTextSize(24);
        canvas.drawText("50",myX/5,myY/2,paint);
        canvas.drawText("100",2*myX/5,myY/2,paint);
        canvas.drawText("150",3*myX/5,myY/2,paint);
        canvas.drawText("200",4*myX/5,myY/2,paint);
        wave.setImageBitmap(bitmap);     //在ImageView中显示bitmap
    }
    @Override   //程序退出前关闭Socket
    protected void onDestroy() {
        super.onDestroy();
        mcom.cancel();
    }
}
